import time

from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.views import Response
# Create your views here.
from myapp.serializers import *
from myapp.models import *
import redis
r=redis.Redis('localhost',6379)
# 打卡视图
class Punch(APIView):
    def get(self,request):
        # method=request.get('method')
        id=request.GET.get('id')

        user = User.objects.get(pk=id)
        # 如果未打卡
        if user.is_work==0:
            # 时间戳存入redis
            r.set(user.name,time.time())
            # 将状态改为上班中
            user.is_work = 1
            user.save()
        else:
            start_secs=float(r.get(user.name))

            end_secs=time.time()
            # 计算上班多少时间
            hours = time.localtime(end_secs).tm_hour-time.localtime(start_secs).tm_hour
            # 判断所处部门
            dep=Department.objects.get(pk=user.did)
            if dep.sid:
                fen=hours*0.1
            else:
                fen = hours*0.5
            # 反序列化添加打卡记录
            data={
                'name':user.name,
                'push_time':time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(start_secs)),
                'work_time':time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(start_secs)),
                'off_time':time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(end_secs)),
                'fen':"+%s"%fen
            }
            card=Card_ser(data=data)
            # 验证字段
            print(card.is_valid())
            if card.is_valid():
                # 进行入库操作
                card.save()
            user.is_work = 0
            user.save()
            r.delete(user.name)
        return Response({'code':200,'msg':'成功'})

class Search(APIView):
    def get(self,request):
        column= request.GET.get('column')
        cards=Card.objects.filter(name__contains=column).order_by('-push_time')
        card_ser= Card_ser(cards,many=True)
        return Response({'data':card_ser.data})

# 升级操作
class Upgrade(APIView):
    def get(self,request):
        id= request.GET.get('id')
        user=User.objects.get(pk=id)

        # 根据用户查询 所属部门
        dep=Department.objects.get(pk=user.did)
        print(dep.sid.id)
        try:
            # 如果所属部门有上级部门
            if dep.sid and user.upgrade ==1:
                # 替换用户sid 为上级部门
                user.did=dep.sid.id
                user.upgrade= 0
                user.save()
        except Exception as e:
            print(e)
        return Response({'code':200,'msg':'升级成功'})


class Show_user(APIView):
    def get(self,request):
        users=User.objects.all()
        user_ser=User_ser(users,many=True)
        return Response({'code':'200','data':user_ser.data})